import { router, addRoutes } from '@/router/index'
import { getToken } from '@/hooks/cookies'
import { elNotification } from '@/hooks/elNotification'
import { useUserStore } from '@/stores/user'
import { showFullLoading, hideFullLoading } from '@/hooks/nprogress'

// 全局前置守卫
let hasGetInfo = false
router.beforeEach(async (to, from, next) => {
    // 显示全屏进度条loading
    showFullLoading()

    const token = getToken()
    const userStore = useUserStore()

    // 没有登陆，强制跳转回登录页
    if (!token && to.path != '/login') {
        elNotification('请先登录', 'error')
        return next('/login')
    }

    // 防止重复登录
    if (token && to.path == '/login') {
        elNotification('请勿重复登录', 'error')
        return next({ path: from.path ? from.path : '/' })
    }

    // 如果用户登录自动获取用户信息，并存储到pinia中
    let hasNewRoutes = false
    if (token && !hasGetInfo) {
        let { menus } = await userStore.getInfoFunction()
        hasGetInfo = true
        // 动态添加路由
        hasNewRoutes = addRoutes(menus)
    }

    // 设置页面标题
    let title = (to.meta.title ? to.meta.title : "") + "-蒂莎后台管理系统"
    document.title = title

    hasNewRoutes ? next(to.fullPath) : next()
})

// 全局后置守卫
router.afterEach((to, from) => hideFullLoading())